import { defineStore } from 'pinia'
import { mapMenusToRoutes } from '@/utils/map-menu'
import { localCache, sessionCache } from '@/utils/cache'
import { TAB_LIST, THEME_COLOR } from '@/global/constant'
import { useAccountStore, useGoodSkuStore } from '@/store'
import type { IOptionItem, ITabItem } from '@/global/types'
import { getRoleList } from '@/service/module/main/system/role'
import { getParentMenuList } from '@/service/module/main/system/menu'
import { getClassifyParentList } from '@/service/module/main/goods/good-classify'
interface IGlobalState {
  tabList: ITabItem[]
  entriesRole: IOptionItem[]
  entriesMenu: any[]
  entireClassify: any[]
}

const useGlobalStore = defineStore('global', {
  state: (): IGlobalState => ({
    tabList: sessionCache.getCache(TAB_LIST) ?? [],
    entriesRole: [],
    entriesMenu: [],
    entireClassify: []
  }),
  actions: {
    // 1.初始化数据
    loadInitialData() {
      if (window.location.href.indexOf('/login') !== -1) return
      // 1.1.动态添加路由
      const accountStore = useAccountStore()
      const menuList = accountStore.menuList
      mapMenusToRoutes(menuList)
      // 1.2.获取角色列表
      this.getRoleListAction()
      // 1.3.获取上级菜单数据
      this.getParentMenuListAction()
      // 1.4.获取全部商户
      const goodSkuStore = useGoodSkuStore()
      goodSkuStore.getMerchantListAction('')
      // 1.5.获取上级分类列表
      this.getClassifyParentListAction()
    },

    // 2.清除用户所有缓存，除了主题色
    cleanLocalUserInfo() {
      const themeColor = localCache.getCache(THEME_COLOR)
      // 不仅是本地的，还要清除这里的，因为退出登录不是刷新，这个tabList还会保存登录前留下的
      // 但是其他的什么菜单数据。用户数据不需要手动置空是因为登陆成功会重新更新数据。
      this.tabList = []
      // local和 session都有缓存
      localCache.clearCache()
      sessionCache.clearCache()
      localCache.setCache(THEME_COLOR, themeColor)
    },

    // 3.获取角色数据
    async getRoleListAction() {
      const roleRes = await getRoleList()
      this.entriesRole = roleRes.data
    },

    // 4.获取菜单列表
    async getParentMenuListAction() {
      const menuRes = await getParentMenuList()
      this.entriesMenu = menuRes.data
    },

    // 5.获取分类上级列表
    async getClassifyParentListAction() {
      const classifyParentListRes = await getClassifyParentList()
      this.entireClassify = classifyParentListRes.data
    }
  }
})

export default useGlobalStore
